/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import com.sun.mail.smtp.*;
import entity.SystemUserEntity;

/**
 *
 * @author wei
 */
public class Mailer {

    private static String password = "";

    public static String doSend(final String sender, String to, String cc, String subject,
            String msgText, String attachementPath, final String password) throws Exception {
        final String pass;
        //for sending forget password notifications
        if (sender.equals("staff.merlion@gmail.com")) {
            pass = "@asdqwe123";
        } else {
            pass = password;
        }

        System.out.println("from: " + sender);
        System.out.println("pass: " + pass);

        Properties prop = System.getProperties();
        prop.put("mail.transport.protocol", "smtp");
        prop.put("mail.smtp.host", "mailauth.comp.nus.edu.sg");
        prop.put("mail.smtp.port", "25");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.debug", "true");

        //Authenticate email and password    
        // Get a handle to the Session.
        Session mySession = Session.getInstance(prop,
                new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("eddie@comp.nus.edu.sg", "@qwerty2911");
                    }
                });
        // Create a Messsage.
        SMTPMessage message = new SMTPMessage(mySession);
        // Set the 'from' address.
        message.setFrom(new InternetAddress(sender));

        // Set the 'to' and 'cc' addresses.
        StringTokenizer tokensTo = new StringTokenizer(to, ";");
        String addr = "";
        while (tokensTo.hasMoreTokens()) {
            addr = tokensTo.nextToken();
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(addr));
        }
        StringTokenizer tokensCC = new StringTokenizer(cc, ";");
        while (tokensCC.hasMoreTokens()) {
            addr = tokensCC.nextToken();
            message.addRecipient(Message.RecipientType.CC,
                    new InternetAddress(addr));
        }


        // Set the 'subject'.
        message.setSubject(subject);

        // Set the date the message would be sent.
        message.setSentDate(new Date());

        // Handle the attachment, if there is one.
        if (attachementPath != null) {
            System.out.println("file processing ....");
            // Set the 'text' as the first body part.
            BodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(msgText);
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);

            BodyPart mbp = new MimeBodyPart();
            String imgName = attachementPath.substring(attachementPath.lastIndexOf("\\") + 1);
            System.out.println("file path: " + attachementPath);
            DataSource src = new FileDataSource(attachementPath);
            mbp.setDataHandler(new DataHandler(src));
            mbp.setFileName(imgName);
            mp.addBodyPart(mbp);
            message.setContent(mp);
        } else {
            // Use the default method if no attachment.
            message.setText(msgText);
        }

        System.out.println("Sending: " + message.toString());
        // Send it.
        SMTPTransport.send(message);
        return "Message Sent Sucessfully.";
    }

    public static void email(SystemUserEntity from, Collection<SystemUserEntity> to,
            Collection<SystemUserEntity> cc, String subject, String msgText)
            throws Exception {
        //send via internal mail
        String recipients = "";
        String ccs = "";

        if (to != null) {
            for (SystemUserEntity user : to) {
                recipients = recipients + user.getContact().getEmail() + ";";
            }
        }

        if (cc != null) {
            for (SystemUserEntity user : cc) {
                ccs = ccs + user.getContact().getEmail() + ";";
            }
        }
//        doSend(from.getContact().getEmail(), recipients, ccs, subject, msgText, 
//                null, from.getPassword());
        doSend(from.getContact().getEmail(), recipients, ccs, subject, msgText,
                null, password);
    }

    public static void getPassword(String pwd) {
        password = pwd;
    }
}
